package base.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * 负载均衡模式的消费者
 *
 * @author Administrator
 * @date 2022/03/31 14:35
 **/
@Slf4j
public class LBConsumer {
    public static void main(String[] args) throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("LoadBalance_Consumer");
        consumer.setNamesrvAddr("192.168.147.151:9876");
        // topic tag
        consumer.subscribe("hello","TagA");
        // 负载均衡模式
        consumer.setMessageModel(MessageModel.CLUSTERING);
        // 回调函数
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                log.info("推送过来的消息数量:{}",msgs.size());
                for (MessageExt msg : msgs) {
                    log.info(new String(msg.getBody()));
                }

                // 返回消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // 开始消费
        consumer.start();
    }
}
